/**
 *  setup.cpp
 *
 *  Copyright (C) 2008  David Andrs <pda@jasnapaka.com>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "stdafx.h"
#include "ce_setup.h"
#include "..\share\defs.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

TCHAR szTodayPluginRoot[] = L"Software\\Microsoft\\Today\\Items\\mCountdown";
TCHAR szEnabled[] = L"Enabled";
TCHAR szInstallDir[] = L"InstallDir";


void RegWriteDword(HKEY hKey, LPCTSTR valueName, DWORD value) {
	RegSetValueEx(hKey, valueName, 0, REG_DWORD, (BYTE *) &value, sizeof(value));
}

BOOL EnableTodayPlugin(BOOL enable = TRUE) {
	HKEY hToday;
	if (::RegOpenKeyEx(HKEY_LOCAL_MACHINE, szTodayPluginRoot, 0, 0, &hToday) == ERROR_SUCCESS) {
		RegWriteDword(hToday, szEnabled, enable ? 1 : 0);
		RegCloseKey(hToday);
		SendMessage(HWND_BROADCAST, WM_WININICHANGE, 0xF2, 0);
		return TRUE;
	}
	else
		return FALSE;
}

BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
    return TRUE;
}

codeINSTALL_INIT
Install_Init(HWND hwndParent, BOOL fFirstCall, BOOL fPreviouslyInstalled, LPCTSTR pszInstallDir) {
	if (fPreviouslyInstalled) {
		EnableTodayPlugin(FALSE);
	}

	return codeINSTALL_INIT_CONTINUE;
}

codeINSTALL_EXIT
Install_Exit(HWND hwndParent, LPCTSTR pszInstallDir, WORD cFailedDirs, WORD cFailedFiles,
	WORD cFailedRegKeys, WORD cFailedRegVals, WORD cFailedShortcuts) {

	// write install path
	HKEY hRoot;
	DWORD dwDisposition;
	if (RegCreateKeyEx(HKEY_CURRENT_USER, REG_KEY_APP, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &hRoot, &dwDisposition) != ERROR_SUCCESS)
		return codeINSTALL_EXIT_UNINSTALL;

	if (RegSetValueEx(hRoot, szInstallDir, 0, REG_SZ, (LPBYTE) pszInstallDir, sizeof(TCHAR) * (lstrlen(pszInstallDir) + 1)) != ERROR_SUCCESS) {
		RegCloseKey(hRoot);
		return codeINSTALL_EXIT_UNINSTALL;
	}

	RegCloseKey(hRoot);

	// activate today plugin
	EnableTodayPlugin(TRUE);

	return codeINSTALL_EXIT_DONE;
}

codeUNINSTALL_INIT
Uninstall_Init(HWND hwndParent, LPCTSTR pszInstallDir) {
	EnableTodayPlugin(FALSE);

	return codeUNINSTALL_INIT_CONTINUE;
}

codeUNINSTALL_EXIT
Uninstall_Exit(HWND hwndParent) {
	RegDeleteKey(HKEY_CURRENT_USER, REG_KEY_APP);
	RegDeleteKey(HKEY_LOCAL_MACHINE, szTodayPluginRoot);

	return codeUNINSTALL_EXIT_DONE;
}
